package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {

    @Autowired
    private StockBackMapper stockBackMapper;

    /**
     * 添加列表到库存回滚表
     *
     * @param orderItemList
     */
    @Transactional
    public void addList(List<OrderItem> orderItemList) {

        for(OrderItem orderItem:orderItemList){
            StockBack stockBack = new StockBack();
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setNum(orderItem.getNum());
            stockBack.setStatus("0");
            stockBack.setCreateTime(new Date());

            stockBackMapper.insert(stockBack);
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 执行库存回滚
     */
    @Transactional
    public void doBack(){
        System.out.println("库存回滚任务开始");

        StockBack stock = new StockBack();
        stock.setStatus("0");//查询未回滚的，并且设置定时任务，保证失败了，还能继续回滚

        List<StockBack> stockBackList = stockBackMapper.select(stock);
        //根据库存表中的库存状态为0，进行回滚
        for(StockBack stockBack:stockBackList){

            //回滚库存
            skuMapper.detectionStock(stockBack.getSkuId(),-stockBack.getNum());

            //回滚销量
            skuMapper.addSaleNum(stockBack.getSkuId(),-stockBack.getNum());

            stockBack.setStatus("1");
            stockBack.setBackTime(new Date());

            stockBackMapper.updateByPrimaryKey(stockBack);
        }

        System.out.println("库存回滚任务结束");
    }
}
